package main

import (
	"bufio"
	"io"
	"jkgo/jk/jklog"
	"os"
	"strconv"
	"strings"
)

type ParseOne struct {
	srcfile string
	dstfile string
}

func NewParseOne(srcfile, dstfile string) (*ParseOne, error) {
	return &ParseOne{
		srcfile: srcfile,
		dstfile: dstfile,
	}, nil
}

func (po *ParseOne) invalidLine(line string) bool {
	i := strings.Index(line, ",")
	if i == -1 {
		return true
	}
	firstData := line[:i]
	_, err := strconv.Atoi(firstData)
	if err != nil {
		return true
	}
	return false
}

func (po *ParseOne) parseSemi(line string, lastline string) (string, bool) {
	if line[0] == '"' {
		return line, true
	} else {
		lastline = lastline + line
		return lastline, false
	}
}

func (po *ParseOne) parseNum(line string, lastline string) (string, bool) {
	if po.invalidLine(line) {
		lastline = lastline + line
		return lastline, false
	}
	return line, true
}

func (po *ParseOne) Parse() error {
	f, err := os.Open(po.srcfile)
	if err != nil {
		return err
	}
	defer f.Close()
	fo, err := os.OpenFile(po.dstfile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
	if err != nil {
		return err
	}
	defer fo.Close()
	reader := bufio.NewReader(f)
	lastline := ""
	returnline := ""
	findMark := false
	parseSemi := false
	valid := false
	for {
		line, _, err := reader.ReadLine()
		if err != nil {
			if err == io.EOF {
				fo.WriteString(lastline)
				break
			}
			jklog.L().Errorln("read Error ", err)
		}

		if !findMark {
			if line[0] == '"' {
				parseSemi = true
			}
			findMark = true
		}
		if parseSemi {
			returnline, valid = po.parseSemi(string(line), lastline)
		} else {
			returnline, valid = po.parseNum(string(line), lastline)
		}

		if valid {
			if len(lastline) > 0 {
				fo.Write([]byte(lastline))
				fo.WriteString("\n")
			}
			lastline = string(line)
		} else {
			lastline = returnline
		}
	}
	return nil
}
